//暂停
#include<stdio.h>
#include <stdlib.h>
#include <math.h>
#include <conio.h>
#include <windows.h>

#define high 20//画面尺寸 
#define width 30
//全局变量

int cells[high][width]; 
int count;
int judge=0;

void HideCursor()
{
	CONSOLE_CURSOR_INFO cursor_info = {1, 0};
	SetConsoleCursorInfo (GetStdHandle (STD_OUTPUT_HANDLE), &cursor_info);
}

void gotoxy(int x,int y)
{
	HANDLE handle=GetStdHandle(STD_OUTPUT_HANDLE);
	COORD pos;
	pos.X=x;
	pos.Y=y;
	SetConsoleCursorPosition(handle,pos);
}

void startup()
{
	HideCursor(); 
	
	int i,j;
	count=15;
	for(i=0;i<high;i++)
	{
		for(j=0;j<width;j++)
		{
			cells[i][j]=rand()%2;
		}
	 } 
}

void show()
{
	gotoxy(0,0);
	
		int i,j;
	for(i=0;i<high;i++)
	{
		for(j=0;j<width;j++)
		{
			if(cells[i][j]==1)
			{
				printf("*");
			}
			else if(cells[i][j]==0)
			{
				printf(" ");
			}
		}
		printf("\n");
	 } 
	
}

void updatewithinput()
{
	
	char input;
	if(kbhit())
	{
		input=getch();
		
		if(input=='a')
		{
			count--;
		}
		if(input=='d')
		{
			count++;
		}
		if(input==27)
		{
			system("pause");
		}	
	}	
}

void updatewithoutinput()
{
	int i,j;
	int tempcells[high][width];//临时存储的数组 
	static int speed=0;
	if(speed<count)
		speed++;
	if(speed==count)
{
	for(i=0;i<high;i++)
	{
		for(j=0;j<width;j++)
		{
			tempcells[i][j]=cells[i][j];	
		}
	 } 
	
	int neibournumber=0;
	for(i=1;i<high-1;i++)
	{
		for(j=1;j<width-1;j++)
		{
			neibournumber=cells[i-1][j-1]+cells[i-1][j]+cells[i-1][j+1]
							+cells[i][j-1]+cells[i][j]+cells[i][j+1]
							+cells[i+1][j-1]+cells[i+1][j]+cells[i+1][j+1];
			
			if(neibournumber==3)
			{
				tempcells[i][j]=1;
			}
			else if(neibournumber==2)
			{
				tempcells[i][j]=cells[i][j];
			}
			else 
			{
				tempcells[i][j]=0;
			}				
		}
	}
	
	for(i=0;i<high;i++)
	{
		for(j=0;j<width;j++)
		{
			cells[i][j]=tempcells[i][j];	
		}
	 }
	 speed=0; 	
}	
	
	
}

int main()
{
	startup();
	
	while(1)
	{
		show();
		updatewithinput();
		updatewithoutinput();
	}	
	return 0;
 } 